package com.opennetexam.manager.facecompare;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Description 人脸识别_File
 * @Author 奶茶
 * Created by on 2018/9/10 14:27.
 */
@Component
public class FaceCompareByFile {

    private static final Logger logger = Logger.getLogger(FaceCompareByFile.class.getName());

    @Value("${FaceCompareUrl}")
    private String faceCompareUrl;

    @Value("${FaceBaseUrl}")
    private String faceBaseUrl;

    @Value("${FaceComapreAppkey}")
    private String faceComapreAppkey;

    @Value("${FaceComapreAppsecret}")
    private String faceComapreAppsecret;

    @Value("${FaceComapreMerchantID}")
    private String faceComapreMerchantID;


    /**
     * 基于图片文件做人脸对比
     * @param sourceFile 对比图
     * @param targetFile 用户认证图
     * @return null 代表请求失败
     */
    public Double faceCompareByFile(File sourceFile,File targetFile){
        //相似度
        Double score = 0.0;
        //获取公共参数集合
        Map<String, String> headers = SignatureUtil.getHeaders(faceComapreAppkey, faceComapreAppsecret);
        try {
            HttpResponse<JsonNode> jsonNodeHttpResponse = Unirest.post(faceCompareUrl + faceBaseUrl)
                    .headers(headers)
                    .header("accept", "application/json")
                    .field("source", sourceFile)
                    .field("target", targetFile)
                    .field("merchantId", faceComapreMerchantID)
                    .asJson();

            if(jsonNodeHttpResponse.getStatus() == HttpStatus.OK.value()){
                logger.info("POST请求["+faceCompareUrl + faceBaseUrl+"]成功，请求结果："+jsonNodeHttpResponse.getBody());
                JsonObject jsonObject = new JsonParser().parse(jsonNodeHttpResponse.getBody().toString()).getAsJsonObject();
                score = jsonObject.get("payload").getAsJsonObject().get("score").getAsDouble();
            }else{
                logger.info("POST请求["+faceCompareUrl + faceBaseUrl+"]失败，请求结果："+jsonNodeHttpResponse.getBody());
                score = null;
            }
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        return score;
    }

}
